﻿<?php 
error_reporting(0);
include 'excel_reader.php';
include 'conn.php';
include 'common.php';?>
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>导入成绩</title>
<body>
<div class="container">
<div class="nav_header">
<?php include 'head.php';?>
</div>
<div class="main_cj_content">	

<p class="welcome">导入成绩:</p>
<hr>
<br />
<br />

<?php

if( $_FILES['grade_file'])
{
	$filename=$_FILES["grade_file"]["name"];
	

	if($_FILES['grade_file']["error"]>0)
	{
		echo "<script>alert('错误: " . $_FILES["grade_file"]["error"] . "');</script>";
		header("Location:admin.php");
	}
	else if(!$filename.strpos(".xls")||(strpos($filename,"xls")!=strlen($filename)-3))
	{
		echo "<script>alert('错误:应该上传.xls后缀的excel文件');</script>";
		header("Location:admin.php");
	}
	else
	{
		$i=1;
		$save_filename="files/users".date("Y-m-d[").$i."].xls";
		while(file_exists("files/users".date("Y-m-d[").$i."].xls"))
		{
			$i=$i+1;
			$save_filename="files/users".date("Y-m-d[").$i."].xls";
				
		}
		move_uploaded_file($_FILES["grade_file"]["tmp_name"],
		$save_filename);

		//sleep(2);
		$excel_data=new Spreadsheet_Excel_Reader($save_filename);
		echo "<p>上传文件成功!上传的文件存储在: " . $save_filename."</p>";
		$rowcount=$excel_data->rowcount();
		if($rowcount<2)
		{
			echo "<script>alert('错误:上传的文件不包含成绩数据，请检查您上传的文件！');</script>";
			header("Location:admin.php");
		}
		$exam_id=$excel_data->val(2, 1);
		//echo $exam_id;
		$exe="";
		mysql_query("BEGIN");
		for( $i=2;$i<=$rowcount;$i++)
		{
	  $student_username=$excel_data->val($i, 2);
	  $student_id_exe="select id from users where username='".  $student_username."'";
	  $student_id_rs=mysql_query($student_id_exe);
	  $student_id_row=mysql_fetch_array($student_id_rs);
	  $student_id=$student_id_row['id'];
	   
	  $sx=$excel_data->val($i, 3);
	  $yw=$excel_data->val($i, 4);
	  $yy=$excel_data->val(($i),5);
	  $wl=$excel_data->val(($i),6);
	  $hx=$excel_data->val(($i),7);
	  $sw=$excel_data->val(($i),8);
	  $ls=$excel_data->val(($i),9);
	  $dl=$excel_data->val(($i),10);
	  $zz=$excel_data->val(($i),11);
	  
	  $exe="insert into grades(userid,sx,yw,yy,wl,hx,sw,ls,dl,zz,exam_id) values(".$student_id.",$sx,$yw,$yy,$wl,$hx,$sw,$ls,$dl,$zz,$exam_id)";
	  
	  $rs=mysql_query($exe);
	  if(!$rs)
	  {
	  	mysql_query("ROLLBACK");
	  	echo "<script language=javascript>alert('你导入的excel表中第".$i ."行数据不符合格式要求，请修改后重新提交!')</script>";
	  	header("Location:admin.php");
	  	exit();

	  }
		}
		mysql_query("COMMIT");
		echo "<p>导入成功！已导入".($rowcount-1)."条数据！";
	}
}
?>
<?php include 'foot.php';?>
</div>
</div>
</body>
</html>